package com.pingpang.websocketchat.send.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.pingpang.util.StringUtil;
import com.pingpang.websocketchat.ChannelManager;
import com.pingpang.websocketchat.ChartUser;
import com.pingpang.websocketchat.ChatGroup;
import com.pingpang.websocketchat.Message;
import com.pingpang.websocketchat.send.ChatSend;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class ChatSendGroup extends ChatSend {

	@Override
	public void send(Message message, ChannelHandlerContext ctx) throws JsonProcessingException {
        
		if(StringUtil.isNUll(message.getGroup().getGroupCode())) {
			return;
		}
		
		message.setFrom(userService.getUser(message.getFrom()));

		Map<String,String> queryMap=new HashMap<String,String>();
		queryMap.put("groupCode",message.getGroup().getGroupCode());
	    ChatGroup group=this.userGroupService.getGroup(queryMap);
	    
	    if(!"0".equals(group.getGroupStatus())) {
	    	ChannelManager.sendAlertMsgByCode(message.getFrom().getUserCode(), "群已被封闭["+message.getGroup().getGroupCode()+"]!");
		    return;
	    }
	    
	    message.setGroup(group);
		
		if (!ChannelManager.isExit(message.getGroup(), message.getFrom().getUserCode())) {
			//ChannelManager.addGroup(message.getGroup(), message.getFrom());
			ChannelManager.sendAlertMsgByCode(message.getFrom().getUserCode(), "你已退群["+message.getGroup().getGroupCode()+"]!");
		    return;
		}
		Set<ChartUser> user = ChannelManager.getGroupUser(message.getGroup());
		for (ChartUser str : user) {
			if (!str.equals(message.getFrom())) {
				ChannelManager.getChannel(str.getUserCode())
						.writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(message)));
			}
			message.setStatus("1");
			message.setAccept(str);// 添加接收方数据
			userMsgService.addMsg(message);
		}
	}

}
